import sys
import os
import datetime
import logging
from selenium import webdriver
import yaml
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
from faker import Faker

rootdir = os.path.dirname(os.path.dirname(__file__))
sys.path.append(rootdir)


class Driver:
    """
    包含各个浏览器的驱动，可指定浏览器进行测试
    """

    @staticmethod
    def browser(driver='chrome', model=None):
        """
        浏览器类型
        Args:
            driver: 指定测试的浏览器类型，默认以chrome运行.
            model: 浏览器运行模式，默认为界面模式，当传入'headless'运行静默模式
        Returns:
            webdriver: webdriver实例对象
        """
        if driver == 'chrome':
            option = webdriver.ChromeOptions()
            if model == 'headless':
                option.add_argument('headless')
            option.add_experimental_option('excludeSwitches', ['enable-logging'])
            return webdriver.Chrome(options=option)
        elif driver == 'firefox':
            return webdriver.Firefox()
        elif driver == 'ie':
            return webdriver.Ie()
        elif driver == 'edge':
            return webdriver.Edge()


class Tools:
    """
    常用工具
    """

    @staticmethod
    def read_yaml(file):
        """
        解析yaml文件中的数据
        Args:
            file: 文件名
        Returns:
            Dict: 字典类型的元素信息
        """
        with open(rootdir+'\\elements\\'+file, 'r', encoding='utf-8') as yamlfile:
            cfg = yaml.load(yamlfile, Loader=yaml.FullLoader)
            return cfg

    @staticmethod
    def send_mail(sender, receiver, authorization, host='smtp.163.com', file=None):
        """
        发送邮件
        Args:
            sender: 发件人邮箱
            receiver: 接收人邮箱
            authorization: 发件人授权码
            host: 发件人邮箱服务器地址，默认设置为stmp.163.com
            file: 要发送的文件的内容，默认为空
        """
        with open(file, 'rb') as f:
            file = f.read()
        time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        msg = MIMEMultipart()
        msg['Subject'] = Header('测试报告' + '_' + time, 'utf-8')  # 标题
        msg['From'] = sender  # 发件人
        msg['To'] = receiver  # 收件人
        body = MIMEText(file, 'html', 'utf-8')  # 正文
        msg.attach(body)
        try:
            email = smtplib.SMTP()
            email = smtplib.SMTP_SSL(host, 465)
            email.login(sender, authorization)
            email.sendmail(sender, receiver, msg.as_string())
            logging.info('测试结果邮件发送成功！')
        except smtplib.SMTPException:
            logging.error('测试结果邮件发送失败！')


class DataFactory:
    """
    辅助生成测试数据
    """

    @property
    def current_time(self):
        """
        当前系统时间
        Returns:
            str: 字符串类型的精确时间
        """
        return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    @property
    def future_date(self):
        """
        未来日期
        Returns:
            str: 字符串类型的日期
        """
        return Faker().future_date().strftime('%Y-%m-%d')

    @property
    def random_text(self):
        """
        随机文本内容
        Returns:
            str: 字符串类型的文本内容
        """
        return Faker().sentence()

    @staticmethod
    def random_number(lenth=6):
        """
        随机数字
        Args:
            lenth: 长度
        Returns:
            str: 字符串类型的随机数
        """
        return Faker().random_number(lenth)

    @property
    def random_username(self):
        """
        随机用户名
        Returns:
            str: 字符串类型的用户名
        """
        return Faker().user_name()
